import NIOSSL
import Fluent
import FluentMySQLDriver
import Vapor
import JWT
import JWTKit

// configures your application
public func configure(_ app: Application) async throws {
    
    app.configureMiddleware()
    
    app.configureDatabase()

    app.migarte()
    
    app.passwords.use(.bcrypt)
    
    // 添加jwt加密算法
    app.jwt.signers.use(.hs256(key: Environment.get("JWT_SALT") ?? "lO4mM5qK9bB1pQ6f"), kid: "a", isDefault: true)
    
    try app.registerRoutes()
    
    app.http.server.configuration.hostname = "0.0.0.0"
}

fileprivate extension Application {
    
    func configureMiddleware() {
        // uncomment to serve files from /Public folder
        // app.middleware.use(FileMiddleware(publicDirectory: app.directory.publicDirectory))
        middleware = .init()
        // 捕捉异常中间件
        middleware.use(ZeusErrorMiddleware.default(environment: environment))
    }
    
    func configureDatabase() {
        // 证书
        var tls = TLSConfiguration.makeClientConfiguration()
        tls.certificateVerification = .none
        // 配置数据库
        databases.use(DatabaseConfigurationFactory.mysql(
            hostname: Environment.get("DATABASE_HOST") ?? "localhost",
            port: Environment.get("DATABASE_PORT").flatMap(Int.init(_:)) ?? 3306,
            username: Environment.get("DATABASE_USERNAME") ?? "root",
            password: Environment.get("DATABASE_PASSWORD") ?? "123456",
            database: Environment.get("DATABASE_NAME") ?? "zeus",
            tlsConfiguration: tls
        ), as: .mysql)
    }
    
    
    func migarte() {
        migrations.add(CreateUser(), CreateRoom())
        migrations.add(CreateDiary(), CreatePhoto())
        migrations.add(CreateEvent())
        migrations.add(UpdateRoomPlant())
        migrations.add(UpdateRoomPetMood())
    }
    
    func registerRoutes() throws {
        get { req async in
            "It works!"
        }
        try register(collection: UserController())
        try register(collection: RoomController())
        try register(collection: PhotoController())
        try register(collection: DiaryController())
        try register(collection: PetController())
    }
    
}


